import React, { useEffect, useState } from "react";
import { Input, Button, Table, Tag } from "antd";
import styles from "./index.less";
import { get4ARoles } from "../../../../services/acceptGroup";

const RolesSelect = props => {
  const {
    rolesOfSelected: listOfSelectedRoles,
    setrolesOfSelected: setlistOfSelectedRoles
  } = props;
  const [listOfRoles, setlistOfRoles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [nameOrId, setnameOrId] = useState();
  const [pageNum, setpageNum] = useState(1);
  const [pageSize, setpageSize] = useState(5);
  const [total, settotal] = useState(0);

  useEffect(() => {
    onSearch();
  }, [pageNum, pageSize]);

  // 查询角色
  function onSearch() {
    const params = {
      pageNum,
      pageSize,
      keyword: nameOrId
    };
    setLoading(true);
    get4ARoles(params).then(res => {
      setlistOfRoles(res.datas);
      settotal(res.totalCount);
      setLoading(false);
    });
  }

  // 已选中组织删除事件
  const onTagDel = key => {
    // 更新tag列表
    setlistOfSelectedRoles(listOfSelectedRoles.filter(o => o.id !== key));
  };
  // 表格页码变化
  const onPageChange = (cur, size) => {
    setpageNum(cur);
    setpageSize(size);
  };
  // 子组织表格column
  const orgColumn = [
    { dataIndex: "id", title: "角色ID" },
    { dataIndex: "roleName", title: "角色名称" }
  ];
  const rowSelection = {
    selectedRowKeys: listOfSelectedRoles.map(o => +o.id),
    onSelect: (record, selected) => {
      if (selected) {
        setlistOfSelectedRoles(listOfSelectedRoles.concat([record]));
      } else {
        setlistOfSelectedRoles(
          listOfSelectedRoles.filter(o => +o.id !== record.id)
        );
      }
    }
  };

  return (
    <div className={styles.root}>
      <div className={styles.searchBox}>
        <Input
          allowClear
          placeholder="请输入角色ID、角色名称"
          value={nameOrId}
          onChange={event => setnameOrId(event.target.value)}
        />
        {/* <div style={{ flex: 1 }} /> */}
        <Button>重置</Button>
        <Button
          loading={loading}
          icon="search"
          type="primary"
          onClick={onSearch}
        >
          查询
        </Button>
      </div>
      <div className={styles.menuTable}>
        <Table
          rowKey="id"
          columns={orgColumn}
          dataSource={listOfRoles}
          rowSelection={rowSelection}
          pagination={{
            pageSize,
            current: pageNum,
            total,
            onChange: onPageChange
          }}
          loading={loading}
        />
      </div>
      <div style={{ padding: "16px 0px" }}>已选：</div>
      <div className={styles.selectedBox}>
        {listOfSelectedRoles.map(rec => (
          <Tag
            style={{ marginBottom: 5 }}
            key={rec.id}
            closable
            onClose={() => onTagDel(rec.id)}
          >
            （{rec.id}）{rec.roleName}
          </Tag>
        ))}
      </div>
    </div>
  );
};

export default RolesSelect;
